package com.yugao.fintech.draper.gateway.handler;

import com.yugao.fintech.draper.gateway.util.WebFluxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关异常通用处理器
 */
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

	@Override
	public Mono<Void> handle(ServerWebExchange exchange, Throwable throwable) {
		ServerHttpResponse response = exchange.getResponse();

		if (response.isCommitted()) {
			return Mono.error(throwable);
		}

		String msg;

		if (throwable instanceof NotFoundException) {
			msg = "未找到该资源";
		}
		else if (throwable instanceof ResponseStatusException) {
			ResponseStatusException responseStatusException = (ResponseStatusException) throwable;
			msg = responseStatusException.getMessage();
		}
		else {
			msg = "内部服务器错误";
		}

		log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), throwable.getMessage());

		return WebFluxUtil.webFluxResponseWriter(response, msg);
	}
}
